#!/usr/bin/perl
##################################################################################
# Copyright (C) 2010  Chris Rutledge <rutledge.chris@gmail.com>
#
# http://code.google.com/p/apsh
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
##################################################################################
use strict;
use lib "/usr/local/lib/perl";
use APSH;

##############################
# Global Variables
##############################
my $DEST            = pop(@ARGV);
my ($RANGE,$RFILE)  = split(/:/, $DEST);
my @LFILES          = @ARGV;
my $RECURSIVE       = undef;

##############################
# Error checking
##############################
if (! @LFILES || ! ($DEST =~ /:/) || ! $RFILE){
   if ((! @LFILES) || !($DEST =~ /:/)){
      print STDERR "Usage: apscp <FILE> <NODEORGROUP[,NODEORGROUP[,..]]>:[DESTINATION] \n";

      if (! ($DEST =~ /:/)){
         print STDERR "\nERROR: no node or group!\n";
      }

      exit(1);
   }else{
      print STDERR "WARNING: No remote file or directory name! Assuming ~/.\n";
   }
}

for (@LFILES){
   if (! -e $_){
      print STDERR "ERROR: local file or directory does not exist!\n";
      exit(1);
   }

   if (-d $_){
      $RECURSIVE = "-r";
   }
}

my @NODES = APSH::GenNodes($RANGE);

APSH::CreateThreads(@NODES);

##############################
# RunCMD()
#
# Get $HOST and $USER from string
# passed and run the command.
##############################
sub RunCMD {
   my $NODECFG = $_[0];

   $APSH::THREADCNT++;

   $NODECFG->{'SSH_OPTS'} =~ s/\-p/\-P/;

   open(FH, "scp $NODECFG->{'SSH_OPTS'} -o BatchMode=yes -o LogLevel=Error $RECURSIVE @LFILES $NODECFG->{'USERNAME'}\@$NODECFG->{'HOSTNAME'}:$RFILE 2>&1 |");

   while(<FH>){
      $APSH::QUEUE->enqueue("$NODECFG->{'HOSTNAME'}: $NODECFG->{'PADDING'}$_");
   }

   close(FH);

   $APSH::QUEUE->enqueue("$NODECFG->{'HOSTNAME'}: $NODECFG->{'PADDING'}...complete\n");

   $APSH::QUEUE->enqueue("--THREAD_FINISHED--");
}
